package com.open.capacity.user.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.easypoi.user.SysUserExcel;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.model.system.SysRole;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.model.system.constants.UserType;
import com.open.capacity.user.config.SystemConfigProperties;
import com.open.capacity.user.dao.SysRoleDao;
import com.open.capacity.user.dao.SysUserDao;
import com.open.capacity.user.dao.SysUserHistoryDao;
import com.open.capacity.user.excel.UserExcel;
import com.open.capacity.user.model.*;
import com.open.capacity.user.service.*;
import com.open.capacity.user.vo.SysUserRelationVo;
import com.open.capacity.user.vo.SysUserVo;
import com.open.capacity.utils.*;
import com.open.capacity.vo.SysUserRelationExtVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao userDao;
    @Autowired
    private SysUserHistoryDao userHistoryDao;

    @Autowired
    private SysDepartmentService departmentService;
    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysRoleDao roleDao;
    @Autowired
    private SysUserRelationService userRelationService;

    @Autowired
    private SysPostService postService;

    @Autowired(required = false)
    private TokenStore redisTokenStore;

    @Autowired
    private SystemConfigProperties configProperties;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysUser updateSysUser(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
            authentication = oAuth2Auth.getUserAuthentication();

            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Auth.getDetails();

            LoginAppUser user = SysUserUtil.getLoginAppUser();

            if (user != null) {

                if (!ObjectUtils.notEqual(user.getId(), sysUser.getId())) {

                    OAuth2AccessToken token = redisTokenStore.readAccessToken(details.getTokenValue());

                    if (token != null) {

                        if (!StringUtils.isBlank(sysUser.getHeadUrl())) {
                            user.setHeadUrl(sysUser.getHeadUrl());
                        }

                        if (!StringUtils.isBlank(sysUser.getNewPassword())) {
                            user.setPassword(sysUser.getNewPassword());
                        }

                        if (!StringUtils.isBlank(sysUser.getNewPassword())) {
                            user.setPassword(sysUser.getNewPassword());
                        }

                        if (!StringUtils.isBlank(sysUser.getNickName())) {
                            user.setNickName(sysUser.getNickName());
                        }

                        if (!StringUtils.isBlank(sysUser.getPhone())) {
                            user.setPhone(sysUser.getPhone());
                        }

                        if (sysUser.getSex() != null) {
                            user.setSex(sysUser.getSex());
                        }

                        UsernamePasswordAuthenticationToken userAuthentication = new UsernamePasswordAuthenticationToken(user,
                                null, user.getAuthorities());

                        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Auth.getOAuth2Request(), userAuthentication);
                        oAuth2Authentication.setAuthenticated(true);
                        redisTokenStore.storeAccessToken(token, oAuth2Authentication);

                    }

                }

            }
        }
        //生成简拼
        String simpleSpelling = PinYinUtil.getAlpha(sysUser.getRealName());
        sysUser.setSimpleSpelling(simpleSpelling);

        userDao.updateByOps(sysUser);
        log.info("修改用户：{}", sysUser);
        return sysUser;
    }

    @Override
    public SysUserRelationExtVo findUserRelationsByObjectId(String objectId) {
        SysUserRelationExtVo vo = new SysUserRelationExtVo();
        List<SysUserRelation> list = userRelationService.findByObjectId(objectId);
        String userIds = "";
        List<SysUser> userSet = new ArrayList<>();
        for (SysUserRelation item : list) {
            if (userIds != "") {
                userIds += ",";
            }
            userIds += item.getUserId();
            userSet.add(userDao.findById(item.getUserId()));
        }
        vo.setUserInfoList(userSet);
        vo.setUserIds(userIds);
        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginAppUser findByUsername(String username) {
        SysUser sysUser = userDao.findByUsername(username);
        if (sysUser == null) {
            return null;
        }
        List<SysUserRelation> list = userRelationService.findByUserId(sysUser.getId());
        String postIds = "", roleIds = "";
        if (!CollectionUtils.isEmpty(list)) {
            for (SysUserRelation relation : list) {
                if (relation.getObjectType().equalsIgnoreCase("role")) {
                    if (roleIds.length() == 0) {
                        roleIds += relation.getObjectId();
                    } else {
                        roleIds += "," + relation.getObjectId();
                    }
                } else if (relation.getObjectType().equalsIgnoreCase("post")) {
                    if (postIds.length() == 0) {
                        postIds += relation.getObjectId();
                    } else {
                        postIds += "," + relation.getObjectId();
                    }
                }
            }
            sysUser.setPostIds(postIds);
            sysUser.setRoleIds(roleIds);
        }
        if (sysUser != null) {
            LoginAppUser loginAppUser = new LoginAppUser();
            BeanUtils.copyProperties(sysUser, loginAppUser);

            Set<SysRole> sysRoles = roleDao.findByUserId(sysUser.getId());
            loginAppUser.setSysRoles(sysRoles);// 设置角色
            loginAppUser.setPostNames(userRelationService.getPostNames(sysUser.getId()));
            return loginAppUser;
        }

        return null;
    }

    @Override
    public SysUser findById(String id) {
        SysUser user = userDao.findById(id);
        if (user == null) {
            return null;
        }
        List<SysUserRelation> list = userRelationService.findByUserId(id);
        String postIds = "", roleIds = "";
        if (!CollectionUtils.isEmpty(list)) {
            for (SysUserRelation relation : list) {
                if (relation.getObjectType().toLowerCase().equals("role")) {
                    if (roleIds.length() == 0) {
                        roleIds += relation.getObjectId();
                    } else {
                        roleIds += "," + relation.getObjectId();
                    }
                } else if (relation.getObjectType().toLowerCase().equals("post")) {
                    if (postIds.length() == 0) {
                        postIds += relation.getObjectId();
                    } else {
                        postIds += "," + relation.getObjectId();
                    }
                }
            }
            user.setPostIds(postIds);
            user.setRoleIds(roleIds);
        }
        return user;
    }

    @Override
    public String findSignature(String id) {
        SysUser user = userDao.findFullById(id);
        Assert.notNull(user, "找不到员工信息");
        return user.getSignature();
    }


    @Override
    public SysUserHistory findLastHistory(String userid) {
        SysUser user = userDao.findById(userid);
        if (user == null) {
            return null;
        }
        SysUserHistory history = userHistoryDao.findLast(userid);
        if (history != null) {
            history.setRealName(user.getRealName());
            history.setDepartmentName(user.getDepartmentName());
            history.setUserCode(user.getUserCode());
        }
        return history;
    }

    @Override
    public String findNameByIds(String ids) {
        String nameStr = "";
        if (StringUtils.isEmpty(ids)) {
            return nameStr;
        }
        for (String userid : ids.split(",")) {
            SysUser user = userDao.findById(userid);
            if (user != null) {
                if (StringUtils.isEmpty(nameStr)) {
                    nameStr += user.getRealName();
                } else {
                    nameStr += "," + user.getRealName();
                }
            }
        }
        return nameStr;
    }

    @Override
    public SysUser findByName(String companyId, String departmentId, String name) {
        return userDao.findByRealname(companyId, departmentId, name);
    }

    @Override
    public SysUser findByGzName(String companyId, String category, String name) {
        if (StringUtil.isNotEmpty(category)) {
            List<String> categoryList = Arrays.asList(category.split(","));
            return userDao.findByCategoryName(companyId, categoryList, name);
        } else {
            return userDao.findByCategoryName(companyId, null, name);
        }
    }

    @Override
    public SysUser findByCode(String companyId, String idnumber) {
        return userDao.findByIDNumber(companyId, idnumber);

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updatePassword(String id, String oldPassword, String newPassword) {
        SysUser sysUser = userDao.findById(id);
        if (StringUtils.isNoneBlank(oldPassword)) {
            if (!passwordEncoder.matches(oldPassword, sysUser.getPassword())) {
                return Result.failed("旧密码错误");
            }
        }

        if (!passwordValid(newPassword)) {
            return Result.failed("密码不符合复杂度要求");
        }

        SysUser user = new SysUser();
        user.setId(id);
        user.setPassword(passwordEncoder.encode(newPassword));

        updateSysUser(user);
        log.info("修改密码：{}", user);
        return Result.succeed("修改成功");
    }

    @Override
    public Result updateSignature(String id, String signature) {
        SysUser sysUser = userDao.findById(id);
        Assert.isTrue(StringUtils.isNotEmpty(signature) && signature.startsWith("data:image/svg+xml"), "签名格式错误");
        SysUser user = new SysUser();
        user.setId(id);
        user.setSignature(signature);

        userDao.updateSignature(id, signature);
        log.info("设置签名：{}", user);
        return Result.succeed("设置成功");
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateStatus(String id, Integer status) {
        SysUser user = new SysUser();
        user.setId(id);
        user.setStatus(status);
        updateSysUser(user);
        log.info("修改状态：{}", user);
        return Result.succeed("修改成功");
    }

    @Override
    public Result updateHeadUrl(String id, String url) {
        SysUser user = new SysUser();
        user.setId(id);
        user.setHeadUrl(url);
        updateSysUser(user);
        log.info("修改头像：{}", user);
        return Result.succeed("修改成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(String id) {
        userRelationService.deleteByUserId(id, null);
        userDao.delete(id);
        return 1;
    }

    @Override
    public int deleteHistory(String id) {
        return userHistoryDao.delete(id);
    }

    @Override
    public List<SysUser> findUsers(Map<String, Object> params) {
        return userDao.findList(params);
    }

    @Override
    public List<SysUserHistory> findUserHistory(String userid) {
        return userHistoryDao.findByUserid(userid);
    }

    @Override
    public List<SysUserHistoryDto> findUserHistorys(String userids) {
        String[] arrIds = userids.split(",");
        return userHistoryDao.findByUserids(arrIds);
    }

    @Override
    public Result saveBankAccount(List<SysUser> sysUsers) {
        for (SysUser user : sysUsers) {
            SysUser model = userDao.findById(user.getId());
            model.setBankAccount(user.getBankAccount());
            try {
                userDao.updateByOps(model);
            } catch (Exception e) {
                log.error("saveBankAccount error:" + e);
            }
        }
        return Result.succeed(sysUsers.size(), "设置成功");
    }


    @Override
    public PageResult<SysUser> pageUsers(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<SysUser> list = userDao.findList(params);
        list.forEach(t -> {
            List<SysUserRelation> objectList = userRelationService.findByUserId(t.getId());
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(objectList)) {
                List<String> postIds = objectList.stream().filter(p -> p.getObjectType().equals("Post")).map(SysUserRelation::getObjectId).collect(Collectors.toList());
                String postNames = "";
                for (String p : postIds) {
                    SysPost post = postService.findById(p);
                    if (StringUtils.isNotEmpty(postNames)) {
                        postNames = postNames + "、" + post.getName();
                    } else {
                        postNames = post.getName();
                    }
                    t.setPostIds(p);
                }
                t.setPostNames(postNames);
            }
        });
        PageInfo<SysUser> pageInfo = new PageInfo(list);

        return PageResult.<SysUser>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveOrUpdate(SysUser sysUser, String keyValue) {
        String username = sysUser.getUserName();
        if (StringUtils.isBlank(username)) {
            //throw new IllegalArgumentException("用户名不能为空");
            return Result.failed("用户名不能为空");
        }

        if (ValidatorUtil.checkPhone(username)) {// 防止用手机号直接当用户名，手机号要发短信验证
            //throw new IllegalArgumentException("用户名要包含英文字符");
            return Result.failed("用户名要包含英文字符");
        }

        if (username.contains("@")) {// 防止用邮箱直接当用户名，邮箱也要发送验证（暂未开发）
            //throw new IllegalArgumentException("用户名不能包含@");
            return Result.failed("用户名不能包含@");
        }

        if (username.contains("|")) {
            //throw new IllegalArgumentException("用户名不能包含|字符");
            return Result.failed("用户名不能包含|字符");
        }

        if (StringUtils.isBlank(sysUser.getNickName())) {
            sysUser.setNickName(username);
        }

        if (StringUtils.isBlank(sysUser.getType())) {
            sysUser.setType(UserType.BACKEND.name());
        }

        if (!StringUtils.isBlank(sysUser.getPhone())) {
            if (!ValidatorUtil.checkPhone(sysUser.getPhone())) {// 防止用手机号直接当用户名，手机号要发短信验证
                //throw new IllegalArgumentException("用户名要包含英文字符");
                return Result.failed("手机号格式不正确");
            }
        }
        if (StringUtils.isNotEmpty(sysUser.getPassword()) && !passwordValid(sysUser.getPassword())) {
            return Result.failed("密码不符合复杂度要求");
        }

        sysUser.setStatus(1);
        sysUser.setCreateTime(new Date());

        if (StringUtils.isEmpty(sysUser.getDepartmentName())) {
            SysDepartment department = departmentService.findById(sysUser.getDepartmentId());
            if (department == null) {
                //throw new IllegalArgumentException("用户名已存在");
                return Result.failed("找不到部门");
            }
            sysUser.setDepartmentName(department.getFullName());
        }

        int i;
        if (StringUtils.isEmpty(keyValue)) {
            SysUser persistenceUser = userDao.findByUsername(sysUser.getUserName());
            if (persistenceUser != null && persistenceUser.getUserName() != null) {
                //throw new IllegalArgumentException("用户名已存在");
                return Result.failed("用户名已存在");
            }
            if (StringUtil.isNotEmpty(sysUser.getPassword())) {
                sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            } else {
                sysUser.setPassword(passwordEncoder.encode(StringUtils.isEmpty(configProperties.getDefaultPassword()) ? "123456" : configProperties.getDefaultPassword()));
            }
            sysUser.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            sysUser.setUpdateTime(sysUser.getCreateTime());

            //生成简拼
            String simpleSpelling = PinYinUtil.getAlpha(sysUser.getRealName());
            sysUser.setSimpleSpelling(simpleSpelling);

            i = userDao.save(sysUser);
        } else {
            sysUser.setId(keyValue);
            sysUser.setUpdateTime(new Date());
            if (sysUser.getPassword().equals("******")) {
                sysUser.setPassword(null);
            } else {
                sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
            }

            //生成简拼
            String simpleSpelling = PinYinUtil.getAlpha(sysUser.getRealName());
            sysUser.setSimpleSpelling(simpleSpelling);

            i = userDao.updateByOps(sysUser);
        }

        if (StringUtils.isNotEmpty(sysUser.getPostIds())) {
            SysUserRelation relationVo = new SysUserRelation();
            relationVo.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            relationVo.setUserId(sysUser.getId());
            relationVo.setObjectType("Post");
            relationVo.setObjectId(sysUser.getPostIds());
            userRelationService.deleteByUserId(sysUser.getId(), "Post");
            userRelationService.save(relationVo);
        }

//		userRoleDao.deleteUserRole(sysUser.getId(), null);
//		List roleIds = Arrays.asList(sysUser.getRoleId().split(","));
//		if (!CollectionUtils.isEmpty(roleIds)) {
//			roleIds.forEach(roleId -> {
//				userRoleDao.saveUserRoles(sysUser.getId(), Long.parseLong(roleId.toString()));
//			});
//		}

        return i > 0 ? Result.succeed(sysUser, "操作成功") : Result.failed("操作失败");
    }

    @Override
    @Transactional
    public Result saveHistory(SysUserHistory history) {
        history.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        history.setCreateTime(new Date());

        SysUserHistory last = userHistoryDao.findLast(history.getUserid());
        int i = 0;
        if (last != null && last.getLevels().equals(history.getLevels()) && last.getJob().equals(history.getJob())) {
            i = 1;
        } else {
            i = userHistoryDao.save(history);
        }

//        SysUser user = userDao.findById(history.getUserid());
//        user.setLevels(history.getLevels());
//        user.setJob(history.getJob());
//        user.setTechnicalLevel(history.getTechnicalLevel());
//        userDao.updateByOps(user);

        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    @Transactional
    public Result saveHistorys(List<SysUserHistoryDto> historys) {

        int i = 0;
        for (SysUserHistoryDto dto : historys) {
            SysUserHistory item = new SysUserHistory();
            item.setLevels(dto.getLevelsNew());
            item.setJob(dto.getJobNew());
            item.setId(dto.getId());
            item.setUserid(dto.getUserid());
            item.setActionTime(dto.getActionTime());
            i += userHistoryDao.updateByOps(item);

            SysUser user = userDao.findById(item.getUserid());
            user.setLevels(item.getLevels());
            user.setJob(item.getJob());
            user.setTechnicalLevel(item.getTechnicalLevel());
            userDao.updateByOps(user);
        }
        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public List<UserExcel> findAllUsers(Map<String, Object> params) {
        List<UserExcel> sysUserExcels = new ArrayList<>();
        List<SysUser> list = userDao.findList(params);

        for (SysUser sysUser : list) {
            UserExcel sysUserExcel = new UserExcel();
            BeanUtils.copyProperties(sysUser, sysUserExcel);
            sysUserExcels.add(sysUserExcel);
        }
        return sysUserExcels;
    }

    @Override
    public Map<String, SysUserVo> getMap() {
        Map<String, SysUserVo> map = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        List<SysUser> list = userDao.findList(params);
        SysUserVo vo;
        for (SysUser item : list) {
            vo = new SysUserVo();
            vo.setCompanyId(item.getCompanyId());
            vo.setDepartmentId(item.getDepartmentId());
            vo.setName(item.getRealName());
            map.put(item.getId(), vo);
        }
        return map;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcel(MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        // 开启excel校验
        params.setNeedVerify(true);

        ExcelImportResult<UserExcel> result = new ExcelImportResult();
        try {
            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                    UserExcel.class, params);
        } catch (Exception e) {
            log.error(e.toString());
            log.error("从文件读取数据错误:{}", e.getMessage());
        }
        if (result.isVerifyFail()) {
            StringBuilder temp = new StringBuilder();
            for (UserExcel entity : result.getFailList()) {
                temp.append("第").append(entity.getRowNum()).append("行的错误是：").append(entity.getErrorMsg());
            }
            throw new Exception("Excel文件校验不通过:" + temp.toString());
        }

        String errMsg = valid(result.getList(), true);
        if (StringUtil.isEmpty(errMsg)) {
            for (UserExcel item : result.getList()) {
                SysUser user = new SysUser();
                BeanUtils.copyProperties(item, user);
                user.setUserName(item.getUserName());
                user.setRealName(item.getRealName());
                SysCompany company = companyService.findByName(item.getCompanyName());
                Assert.notNull(company, "找不到机构" + item.getCompanyName());
                user.setCompanyId(company.getId());
                SysDepartment department = departmentService.findByName(company.getId(), item.getDepartmentName());
                Assert.notNull(department, "找不到部门" + item.getDepartmentName());
                user.setDepartmentId(department.getId());
                user.setDepartmentName(department.getFullName());
                if (StringUtil.isNotEmpty(item.getPassword())) {
                    user.setPassword(item.getPassword());
                } else {
                    user.setPassword(StringUtils.isEmpty(configProperties.getDefaultPassword()) ? "123456" : configProperties.getDefaultPassword());
                }

                user.setStatus(1);
                user.setPhone(item.getPhone());
                user.setDescription("");
                user.setType("BACKEND");
                Result rs = saveOrUpdate(user, null);
                if (!rs.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
                    throw new Exception(rs.getResp_msg());
                }
            }

            return result.getList().size();
        } else {
            throw new Exception(errMsg);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importBankAccount(MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        // 开启excel校验
        params.setNeedVerify(true);

        ExcelImportResult<UserExcel> result = new ExcelImportResult();
        try {
            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                    UserExcel.class, params);
        } catch (Exception e) {
            log.error(e.toString());
            log.error("从文件读取数据错误:{}", e.getMessage());
        }
        if (result.isVerifyFail()) {
            StringBuilder temp = new StringBuilder();
            for (UserExcel entity : result.getFailList()) {
                temp.append("第").append(entity.getRowNum()).append("行的错误是：").append(entity.getErrorMsg());
            }
            throw new Exception("Excel文件校验不通过:" + temp.toString());
        }

        String errMsg = validBankAccount(result.getList(), false);
        List<SysUser> userList = new ArrayList<>();
        if (StringUtil.isEmpty(errMsg)) {
            for (UserExcel item : result.getList()) {
                SysCompany company = companyService.findByName(item.getCompanyName());
                Assert.notNull(company, "找不到机构" + item.getCompanyName());
                SysDepartment department = departmentService.findByName(company.getId(), item.getDepartmentName());
                Assert.notNull(department, "找不到部门" + item.getDepartmentName());
                SysUser user = userDao.findByRealname(company.getId(), department.getId(), item.getRealName());
                Assert.notNull(user, "找不到职工" + item.getRealName());
                user.setBankAccount(item.getBankAccount());
                userList.add(user);
            }

            Result rs = saveBankAccount(userList);
            if (!rs.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
                throw new Exception(rs.getResp_msg());
            }
            return result.getList().size();
        } else {
            throw new Exception(errMsg);
        }
    }

    /**
     * 校验员工数据导入
     *
     * @param list
     * @param checkExists
     * @return
     */
    private String valid(List<UserExcel> list, Boolean checkExists) {
        String errorMsg = "";
        int i = 1;
        for (UserExcel item : list) {
            i++;
            if (StringUtil.isEmpty(item.getUserName())) {
                errorMsg += (i + "行账号不能为空");
            }
            if (checkExists) {
                SysUser persistenceUser = userDao.findByUsername(item.getUserName());
                if (persistenceUser != null && persistenceUser.getUserName() != null) {
                    errorMsg += "账号" + item.getUserName() + "已存在";
                }
            }
            SysCompany company = companyService.findByName(item.getCompanyName());
            if (company == null) {
                errorMsg += "机构" + item.getCompanyName() + "不存在";
            } else {
                SysDepartment department = departmentService.findByName(company.getId(), item.getDepartmentName());
                if (department == null) {
                    errorMsg += "部门" + item.getDepartmentName() + "不存在";
                }
            }
            if (StringUtil.isEmpty(item.getCategory())) {
                errorMsg += (i + "行员工类型不能为空");
            }
//            if (StringUtil.isEmpty(item.getPosition())) {
//                errorMsg += (i + "行职称不能为空");
//            }
//            if (StringUtil.isEmpty(item.getLevel())) {
//                errorMsg += (i + "行职级不能为空");
//            }
        }
        return errorMsg;
    }

    /**
     * 校验银行账号数据导入
     *
     * @param list
     * @param checkExists
     * @return
     */
    private String validBankAccount(List<UserExcel> list, Boolean checkExists) {
        String errorMsg = "";
        int i = 1;
        for (UserExcel item : list) {
            i++;
            if (StringUtil.isEmpty(item.getUserName())) {
                errorMsg += (i + "行账号不能为空");
            }
            if (checkExists) {
                SysUser persistenceUser = userDao.findByUsername(item.getUserName());
                if (persistenceUser != null && persistenceUser.getUserName() != null) {
                    errorMsg += "账号" + item.getUserName() + "已存在";
                }
            }
            SysCompany company = companyService.findByName(item.getCompanyName());
            if (company == null) {
                errorMsg += "机构" + item.getCompanyName() + "不存在";
            } else {
                SysDepartment department = departmentService.findByName(company.getId(), item.getDepartmentName());
                if (department == null) {
                    errorMsg += "部门" + item.getDepartmentName() + "不存在";
                }
            }
        }
        return errorMsg;
    }

    //检查密码复杂度是否符合要求
    private boolean passwordValid(String password) {
        boolean result = true;
        if (configProperties.getEnabled() != null && configProperties.getEnabled().equals(1)) {//判断是否开启校验
            result = password.matches(configProperties.getPasswordRegular());
        }
        return result;
    }
}
